class EarthquakeMonitor {
    constructor() {
        this.map = null;
        this.earthquakeLayer = null;
        this.autoRefreshInterval = null;
        this.isAutoRefresh = false;
        this.currentFilter = 'all';
        this.earthquakeData = [];
        
        this.init();
    }

    init() {
        this.initMap();
        this.bindEvents();
        this.loadEarthquakeData();
    }

    initMap() {
        // 初始化地图
        this.map = L.map('map', {
            center: [20, 0],
            zoom: 2,
            zoomControl: true,
            attributionControl: true
        });

        // 添加地图图层
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© OpenStreetMap contributors | 地震数据来源: USGS',
            maxZoom: 18
        }).addTo(this.map);

        // 创建地震标记图层组
        this.earthquakeLayer = L.layerGroup().addTo(this.map);
    }

    bindEvents() {
        // 刷新按钮
        document.getElementById('refresh-btn').addEventListener('click', () => {
            this.loadEarthquakeData();
        });

        // 自动刷新按钮
        document.getElementById('auto-refresh-btn').addEventListener('click', () => {
            this.toggleAutoRefresh();
        });

        // 震级筛选
        document.getElementById('magnitude-filter').addEventListener('change', (e) => {
            this.currentFilter = e.target.value;
            this.filterEarthquakes();
        });
    }

    async loadEarthquakeData() {
        const loading = document.getElementById('loading');
        loading.style.display = 'flex';

        try {
            // USGS API - 获取过去24小时的地震数据
            const response = await fetch('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson');
            const data = await response.json();
            
            this.earthquakeData = data.features;
            this.displayEarthquakes();
            this.updateStats();
            
        } catch (error) {
            console.error('加载地震数据失败:', error);
            this.showError('无法加载地震数据，请检查网络连接');
        } finally {
            loading.style.display = 'none';
        }
    }

    displayEarthquakes() {
        // 清除现有标记
        this.earthquakeLayer.clearLayers();

        this.earthquakeData.forEach(earthquake => {
            const coords = earthquake.geometry.coordinates;
            const props = earthquake.properties;
            
            // 经纬度 (注意：GeoJSON格式是 [经度, 纬度])
            const lat = coords[1];
            const lng = coords[0];
            const magnitude = props.mag;
            
            if (!magnitude || magnitude < 0) return;

            // 根据震级确定标记样式
            const markerStyle = this.getMarkerStyle(magnitude);
            
            // 创建圆形标记
            const marker = L.circleMarker([lat, lng], markerStyle);
            
            // 创建弹窗内容
            const popupContent = this.createPopupContent(props, coords);
            marker.bindPopup(popupContent);
            
            // 添加到图层
            this.earthquakeLayer.addLayer(marker);
        });

        this.filterEarthquakes();
    }

    getMarkerStyle(magnitude) {
        let color, fillColor, radius;
        
        if (magnitude < 3.0) {
            color = '#48bb78';
            fillColor = '#48bb78';
            radius = 4;
        } else if (magnitude < 4.0) {
            color = '#38b2ac';
            fillColor = '#38b2ac';
            radius = 6;
        } else if (magnitude < 5.0) {
            color = '#4299e1';
            fillColor = '#4299e1';
            radius = 8;
        } else if (magnitude < 6.0) {
            color = '#ed8936';
            fillColor = '#ed8936';
            radius = 12;
        } else if (magnitude < 7.0) {
            color = '#f56565';
            fillColor = '#f56565';
            radius = 16;
        } else {
            color = '#9f1239';
            fillColor = '#9f1239';
            radius = 20;
        }

        return {
            color: color,
            fillColor: fillColor,
            fillOpacity: 0.7,
            weight: 2,
            radius: radius
        };
    }

    createPopupContent(props, coords) {
        const magnitude = props.mag || 0;
        const place = props.place || '未知地点';
        const time = new Date(props.time).toLocaleString('zh-CN');
        const depth = coords[2] || 0;
        const url = props.url;
        
        // 获取震级对应的颜色
        const magnitudeColor = this.getMagnitudeColor(magnitude);
        
        return `
            <div class="popup-content">
                <div class="popup-title">
                    🌍 地震信息
                </div>
                <div class="popup-info">
                    <div class="popup-row">
                        <span class="popup-label">地点:</span>
                        <span class="popup-value">${place}</span>
                    </div>
                    <div class="popup-row">
                        <span class="popup-label">震级:</span>
                        <span class="magnitude-badge" style="background-color: ${magnitudeColor}">
                            M ${magnitude.toFixed(1)}
                        </span>
                    </div>
                    <div class="popup-row">
                        <span class="popup-label">深度:</span>
                        <span class="popup-value">${depth.toFixed(1)} km</span>
                    </div>
                    <div class="popup-row">
                        <span class="popup-label">时间:</span>
                        <span class="popup-value">${time}</span>
                    </div>
                    <div class="popup-row">
                        <span class="popup-label">坐标:</span>
                        <span class="popup-value">${coords[1].toFixed(3)}°, ${coords[0].toFixed(3)}°</span>
                    </div>
                    ${url ? `<div class="popup-row">
                        <a href="${url}" target="_blank" style="color: #4299e1; text-decoration: none; font-weight: 500;">
                            📊 查看详细信息
                        </a>
                    </div>` : ''}
                </div>
            </div>
        `;
    }

    getMagnitudeColor(magnitude) {
        if (magnitude < 3.0) return '#48bb78';
        if (magnitude < 4.0) return '#38b2ac';
        if (magnitude < 5.0) return '#4299e1';
        if (magnitude < 6.0) return '#ed8936';
        if (magnitude < 7.0) return '#f56565';
        return '#9f1239';
    }

    filterEarthquakes() {
        this.earthquakeLayer.eachLayer(layer => {
            const magnitude = this.getMagnitudeFromLayer(layer);
            let show = true;

            switch (this.currentFilter) {
                case 'significant':
                    show = magnitude >= 4.5;
                    break;
                case 'major':
                    show = magnitude >= 6.0;
                    break;
                default:
                    show = true;
            }

            if (show) {
                layer.setStyle({ opacity: 1, fillOpacity: 0.7 });
            } else {
                layer.setStyle({ opacity: 0.3, fillOpacity: 0.1 });
            }
        });
    }

    getMagnitudeFromLayer(layer) {
        // 从图层的半径推断震级（简化方法）
        const radius = layer.options.radius;
        if (radius <= 4) return 2.5;
        if (radius <= 6) return 3.5;
        if (radius <= 8) return 4.5;
        if (radius <= 12) return 5.5;
        if (radius <= 16) return 6.5;
        return 7.5;
    }

    updateStats() {
        const count = this.earthquakeData.length;
        const maxMag = Math.max(...this.earthquakeData.map(eq => eq.properties.mag || 0));
        const now = new Date().toLocaleString('zh-CN');

        document.getElementById('earthquake-count').textContent = count;
        document.getElementById('max-magnitude').textContent = maxMag > 0 ? `M ${maxMag.toFixed(1)}` : '-';
        document.getElementById('last-update').textContent = now;
    }

    toggleAutoRefresh() {
        const btn = document.getElementById('auto-refresh-btn');
        
        if (this.isAutoRefresh) {
            // 停止自动刷新
            clearInterval(this.autoRefreshInterval);
            this.isAutoRefresh = false;
            btn.textContent = '⏰ 自动刷新: 关闭';
            btn.classList.remove('active');
        } else {
            // 开始自动刷新 (每5分钟)
            this.autoRefreshInterval = setInterval(() => {
                this.loadEarthquakeData();
            }, 5 * 60 * 1000);
            this.isAutoRefresh = true;
            btn.textContent = '⏰ 自动刷新: 开启';
            btn.classList.add('active');
        }
    }

    showError(message) {
        // 创建错误提示
        const errorDiv = document.createElement('div');
        errorDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #f56565;
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            box-shadow: 0 4px 16px rgba(245, 101, 101, 0.3);
            z-index: 10000;
            font-weight: 500;
        `;
        errorDiv.textContent = message;
        
        document.body.appendChild(errorDiv);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (errorDiv.parentNode) {
                errorDiv.parentNode.removeChild(errorDiv);
            }
        }, 3000);
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    new EarthquakeMonitor();
});